package com.xingfei.blog.controller;

import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.common.URLEnum;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.constants.GeneralConstants;
import com.xingfei.blog.controller.base.BaseController;
import com.xingfei.blog.dto.ArticleDTO;
import com.xingfei.blog.dto.UserInfoDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.result.ServiceResult;
import com.xingfei.blog.service.WebArticleService;
import com.xingfei.blog.service.WebPersonalService;
import com.xingfei.blog.service.WebUserInfoService;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.CookieUtil;
import com.xingfei.blog.utils.EMailSenderUtil;
import com.xingfei.blog.utils.UserThreadLocal;
import com.xingfei.blog.vo.ArticleVo;
import com.xingfei.blog.vo.UserInfoVO;
import com.xingfei.blog.vo.UserVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 个人中心相关（因考虑以后扩展，特将个人中心抽取）
 *
 * @author: chenxingfei
 * @time: 2017/4/1  22:47
 * To change this template use File | Settings | File Templates.
 */
@RequestMapping(value = "personal")
@Controller
public class PersonalController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(PersonalController.class);

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private WebPersonalService webPersonalService;

    @Autowired
    private WebArticleService webArticleService;

    @Autowired
    private WebUserInfoService webUserInfoService;

    @Autowired
    private RedisClusterUtil redisCluster;

    private static String Profix_Email = "email:";
    /**
     * 用户个人中心
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "center")
    public ModelAndView getUserInfo(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/personal/jianyi-personal-center");
        UserVO userVO = UserThreadLocal.get();
        modelAndView.addObject("user", userVO);
        //加载用户数据
        //加载首页文章列表
        ArticleDTO articleDTO = new ArticleDTO();
        articleDTO.setArticleType(1l);
        articleDTO.setUserId(userVO.getId());
        List<ArticleVo> articleVos = this.webArticleService.listByPage(articleDTO, 1, GeneralConstants.PAGE_SIZE);
        if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(articleVos)) {
            for (ArticleVo articleVo : articleVos) {
                webArticleService.appendArticleOtherData(articleVo, userVO);
                webArticleService.appendUserInfo(articleVo);
            }
            request.getSession().setAttribute("personal_articles", articleVos);
        }

        List<UserInfoDTO> infoDTOS = webUserInfoService.listRecommendAuthor();
        if (CollectionUtils.isNotEmpty(infoDTOS)) {
            request.getSession().setAttribute("recommends", infoDTOS);
        }
                    /*}
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }*/
        return modelAndView;
    }

    /**
     * 设置
     *
     * @param request
     * @return
     */
    @RequestMapping("/settings")
    public ModelAndView settings(HttpServletRequest request) {
        UserVO user = UserThreadLocal.get();
        request.getSession().setAttribute("user", user);
        ModelAndView modelAndView = new ModelAndView("/personal/jianyi-personal-setting");
        return modelAndView;
    }

    /**
     * 更新用户头像
     *
     * @return
     */
    @RequestMapping(value = "/avatarImg", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonResult avatarImg(HttpServletRequest request, @RequestBody Map<String, String> map) {

        JsonResult jsonResult = null;
        //调用upload模块 IMG_TYPE_AVATAR
        try {
            if (map != null) {
                String imgSrc = map.get("imgSrc");
                String oldImgSrc = map.get("oldImgSrc");
                UserVO userVO = null;
                String token = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    try {
                        Cookie cookie2 = CookieUtil.getCookie(request, "token");
                        if (cookie2 != null) {
                            token = cookie2.getValue();
                            if (StringUtils.isNotEmpty(token)) {
                                userVO = webUserService.getUser4Redis(token);
                            } else {
                                jsonResult = new JsonResult(true, ErrorConstants.SERVER_ERROR, "请重新登陆");
                                return jsonResult;
                            }
                        } else {
                            jsonResult = new JsonResult(true, ErrorConstants.SERVER_ERROR, "请重新登陆");
                            return jsonResult;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("message error:", e);
                    }
                }
                //调用上传接口,上传图片
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost httpRequest = new HttpPost(URLEnum.REMOTEIMG_URL.getValue());
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                //上传base64编码图片，需要去除前缀data:image/jpeg;base64, data:image/png;base64,
                imgSrc = imgSrc.substring(imgSrc.indexOf("base64,") + 7, imgSrc.length());
                params.add(new BasicNameValuePair("imgStr", imgSrc));
                params.add(new BasicNameValuePair("imgType", "avatar"));
                httpRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
                CloseableHttpResponse execute = httpClient.execute(httpRequest);
                HttpEntity entity = execute.getEntity();
                String requestResult = EntityUtils.toString(entity);
                if (StringUtils.isNotBlank(requestResult)) {
                    //上传成功 更新db图片路径
                    UserInfoDTO userInfo = new UserInfoDTO();
                    userInfo.setUserId(userVO.getId());
                    userInfo.setAvatarUrl(requestResult);
                    boolean result = webUserInfoService.updateUserInfoField(userInfo);
                    if (result && oldImgSrc.contains("files")) {
                        //删除原有头像
                        oldImgSrc = oldImgSrc.substring(oldImgSrc.indexOf("files"), oldImgSrc.length());
                        CloseableHttpClient httpClient2 = HttpClients.createDefault();
                        HttpPost httpPost = new HttpPost(URLEnum.DELETEIMG_URL.getValue());
                        List<NameValuePair> params2 = new ArrayList<NameValuePair>();
                        params2.add(new BasicNameValuePair("path", oldImgSrc));
                        httpPost.setEntity(new UrlEncodedFormEntity(params2, Consts.UTF_8));
                        CloseableHttpResponse execute2 = httpClient2.execute(httpPost);
                        HttpEntity entity2 = execute2.getEntity();
                        String requestResult2 = EntityUtils.toString(entity2);
                        System.out.println(requestResult2.equals("0") ? "删除原有头像失败" : "删除原有头像成功");
                        //更新redis缓存
                        UserInfoVO userInfoVO = userVO.getUserInfoVO();
                        userInfoVO.setAvatarUrl(requestResult);
                        userVO.setUserInfoVO(userInfoVO);
                        boolean result2 = webPersonalService.updateRedis(token, userVO);
                        if (result2) {
                            //success
                            jsonResult = new JsonResult(true, ErrorConstants.SERVER_SUCCESS, "/personal/settings");
                            return jsonResult;
                        } else {
                            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "更新缓存失败");
                            return jsonResult;
                        }
                    } else {
                        jsonResult = new JsonResult(true, ErrorConstants.SERVER_SUCCESS, "/personal/settings");
                        return jsonResult;
                    }
                }
            }

        } catch (IOException e) {
            logger.error("更新用户头像 avatarImg error：" + e.toString());
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "更新用户头像错误");
            return jsonResult;
        } catch (Exception e) {
            logger.error("更新用户头像 avatarImg error：" + e.toString());
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "更新用户头像错误");
            return jsonResult;
        }
        return jsonResult;
    }

    /**
     * 首页加载更多数据调用接口
     *
     * @param page
     * @return
     */
    @RequestMapping("/listMyArticles")
    @ResponseBody
    public List<ArticleVo> listMyArticles(Integer page) {
        ArticleDTO articleDto = new ArticleDTO();
        UserVO userVO = UserThreadLocal.get();
        if (userVO == null) {
            return null;
        }
        articleDto.setUserId(userVO.getId());
        List<ArticleVo> articleVos = this.webArticleService.listByPage(articleDto, page, GeneralConstants.PAGE_SIZE);
        if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(articleVos)) {
            for (ArticleVo articleVo : articleVos) {
                webArticleService.appendArticleOtherData(articleVo, userVO);
                webArticleService.appendUserInfo(articleVo);
            }
        }
        return articleVos;
    }

    @RequestMapping("/msg")
    public ModelAndView msg(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/personal/jianyi-personal-msg");
        return modelAndView;
    }

    /**
     * send email
     */
    @RequestMapping(value = "/sendEmail/{email:.+}",method = RequestMethod.GET)
    public @ResponseBody JsonResult sendEmail(HttpServletRequest request,@PathVariable String email) {
        JsonResult jsonResult;
        String token = CookieUtil.getCookieValue(request,"token");
        //发送邮件
            boolean sendEmailResult = EMailSenderUtil.sendEmailToUpdateEmail(email,token);
            //发送邮件成功跳转
            if (sendEmailResult) {
                logger.info(email+":邮件发送成功！");
                //redis记录邮件信息  30分钟
                redisCluster.set(Profix_Email+token,email,60*30);
                jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "发送邮件成功，请查收确认！");
                return jsonResult;
            } else {
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
        return jsonResult;
    }
    /**
     * 校验手机验证码
     */
    @RequestMapping(value = "/checkMobileCode", method = RequestMethod.POST)
    public @ResponseBody JsonResult checkMessageCode(HttpServletRequest request, @RequestBody Map<String,String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        JsonResult jsonResult;
        String s = redisCluster.get(phone);
        UserVO userVO = UserThreadLocal.get();
        String token = CookieUtil.getCookieValue(request,"token");
        if (StringUtils.isNotBlank(s) && StringUtils.isNotBlank(code)) {
            if (com.alibaba.dubbo.common.utils.StringUtils.isEquals(s, code)) {
                //验证成功,更改用户信息
                boolean flag = webPersonalService.updateUserPhone(userVO.getId(),phone);
                //重置缓存
                userVO.setPhone(phone);
                UserInfoVO userInfoVO = userVO.getUserInfoVO();
                userInfoVO.setPhone(phone);
                userVO.setUserInfoVO(userInfoVO);
                webPersonalService.updateRedis(token, userVO);
                request.getSession().setAttribute("user", userVO);
                //TODO 未做清空手机验证码缓存
                jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "绑定成功！");
            }else {
                jsonResult = new JsonResult(false, ErrorConstants.RESULT_PHONE_CODE_REPET, "验证码错误,请重试");
            }
        }else{
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
        }
        return jsonResult;
    }

    /**
     * change user info
     */
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public @ResponseBody JsonResult updateUserInfo(HttpServletRequest request,@RequestBody UserInfoDTO userInfoDTO){
        JsonResult jsonResult;
        UserVO userVO = UserThreadLocal.get();
        userInfoDTO.setUserId(userVO.getId());
        String token = CookieUtil.getCookieValue(request,"token");
        ServiceResult<Boolean> serviceResult = webUserInfoService.updateUserInfoField2(userInfoDTO);
        if (serviceResult != null && serviceResult.getCode() == ErrorConstants.RES_SUCCESS) {
            if(serviceResult.getResult()){
                //重置缓存
                if(StringUtils.isNotBlank(userInfoDTO.getUserName())){
                    userVO.setUserName(userInfoDTO.getUserName());
                }
                UserInfoVO userInfoVO = userVO.getUserInfoVO();
                if(StringUtils.isNotBlank(userInfoDTO.getUserName())){
                    userInfoVO.setUserName(userInfoDTO.getUserName());
                }
                userInfoVO.setSex(userInfoDTO.getSex());
                if(StringUtils.isNotBlank(userInfoDTO.getDescription())){
                    userInfoVO.setDescription(userInfoDTO.getDescription());
                }
                userInfoVO.setBirthday(userInfoDTO.getBirthday());
                userVO.setUserInfoVO(userInfoVO);
                webPersonalService.updateRedis(token, userVO);
                request.getSession().setAttribute("user", userVO);
                jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "保存成功！");
            }else{
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, serviceResult.getErrMsg());
            }
        }else {
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR,"服务器错误！");
        }

        return jsonResult;
    }

    /**
     * check username
     */
    @RequestMapping(value = "/checkUserName",method = RequestMethod.GET)
    public @ResponseBody JsonResult checkUserName(@RequestParam String userName){
        JsonResult jsonResult;
        if(StringUtils.isNotBlank(userName)){
            //根据用户名查询
            try {
                boolean b = webPersonalService.checkUserName(userName);
                if(!b){
                    jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS,null);
                }else{
                    jsonResult = new JsonResult(ErrorConstants.RESULT_USERNAME_REPET,"昵称已存在，请重新填写哦");
                }
            } catch (Exception e) {
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
            return jsonResult;
        }
        return null;
    }

}
